home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 283 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  62 lines

  1. Path: sundog.tiac.net!usenet
  2. From: page@tiac.net (Chris Page)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Constructor Exceptions
  5. Date: Wed, 03 Jan 1996 15:05:55 GMT
  6. Organization: The Internet Access Company
  7. Message-ID: <4ce68n$8u4@sundog.tiac.net>
  8. References: <4bud9g$pv5@oxy.rust.net> <4cbhcl$kst@dawn.mmm.com>
  9. NNTP-Posting-Host: page.tiac.net
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. kjhopps@mmm.com (Kevin J Hopps) wrote:
  13.  
  14. :Paul Gunn (pgunn@mail.cbf.com) wrote:
  15.  
  16. :> I use Microsoft Visual C++, and have been gradually making use of
  17. :> exceptions in my code. I'm interested in using exceptions in my
  18. :> constructor code, but according to a MS article, when an exception is
  19. :> thrown from a constructor on a heap object, the memory will not be
  20. :> freed.
  21.  
  22. :> Is this behavior parculiar to the Microsoft implementation or is it
  23. :> generally the case?
  24.  
  25. :It is not generally the case.  Compilers that adhere to the standard
  26. :will produce code that does not leak memory in this way.
  27.  
  28. Sure, they'll clean up 'this', but the programmer is responsible for
  29. any and all heap memory allocated within the body of constructor.
  30.  
  31. For example,
  32.  
  33. class Foo {
  34.     public:
  35.     Foo(int initNum) : mNum(initNum),          // # 0
  36.             m1Ptr(new Part1),       // # 1
  37.             m2Ptr(new Part2) {};   // # 2 
  38.     private:
  39.     int mNum;
  40.     Part1 *m1Ptr;
  41.     Part2 *m2Ptr;
  42. };
  43.  
  44. Let's assume a Foo is created from the heap:
  45.  
  46.     Foo *myFooPtr = new Foo(12);
  47.  
  48. And an exception is thrown (xalloc) when 'new Part2' (#2) fails.
  49.  
  50. The storage allocated for Foo which is sizeof(Foo) is cleaned up.  The
  51. memory allocated on line #2 using 'new Part1' is a leaked.
  52.  
  53.  
  54. The solution to this problem is to use the "resource allocation is
  55. class initialization" technique, which has been discussed in the news
  56. group many time before.
  57.  
  58. -Chris
  59.  
  60.  
  61.  
  62.